package com.xin.springbootjurisdiction.service.impl;

import com.xin.springbootjurisdiction.dataobject.RoleInfo;
import com.xin.springbootjurisdiction.repository.RoleInfoRepository;
import com.xin.springbootjurisdiction.service.RoleInfoService;
import com.xin.springbootjurisdiction.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * 角色Service
 */
@Service
@Slf4j
public class RoleInfoServiceImpl implements RoleInfoService{
    @Autowired
    private RoleInfoRepository roleInfoRepository;
    /**
     *创建角色
     * @param roleInfo
     * @return
     */
    @Override
    @Transactional
    public RoleInfo create(RoleInfo roleInfo) {
        //参数是否存在
        if (ObjectUtils.isEmpty(roleInfo)){
              return null;
        }
        //设置ID
        roleInfo.setRoleId(KeyUtil.genUniqueKey());
        RoleInfo save = roleInfoRepository.save(roleInfo);
        if (!ObjectUtils.isEmpty(save)){
             return save;
        }
        return null;
    }

    /**
     * 删除角色
     * @param roleId
     * @return
     */
    @Override
    @Transactional
    public boolean delete(String roleId) {
        RoleInfo roleInfo = findOne(roleId);
        if (ObjectUtils.isEmpty(roleInfo)){
              return false;
        }
        roleInfoRepository.delete(roleInfo);
        return true;
    }

    /**
     * 查询角色
     * @param roleId
     * @return
     */
    @Override
    public RoleInfo findOne(String roleId) {
        if (StringUtils.isEmpty(roleId)){
              return null;
        }
        RoleInfo roleInfo = roleInfoRepository.findOne(roleId);
        if (!ObjectUtils.isEmpty(roleInfo)){
             return roleInfo;
        }
        return null;
    }

    /**
     * 更新角色
     * @param roleInfo
     * @return
     */
    @Override
    @Transactional
    public RoleInfo update(RoleInfo roleInfo) {
        if (ObjectUtils.isEmpty(roleInfo)){
              return null;
        }
        //查找是否存在
        RoleInfo one = findOne(roleInfo.getRoleId());
        if (ObjectUtils.isEmpty(one)){
              return null;
        }
        one.setName(roleInfo.getName());
        RoleInfo save = roleInfoRepository.save(one);
        if (!ObjectUtils.isEmpty(save)){
             return save;
        }
        return null;
    }
}
